package com.bzchao.oauth.config.security;

import com.bzchao.oauth.bean.SysModule;
import com.bzchao.oauth.bean.SysRole;
import com.bzchao.oauth.bean.SysUser;
import com.bzchao.oauth.service.RoleService;
import com.bzchao.oauth.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 〈用于提供给spring security访问数据库〉
 *
 * @author coach tam
 * @create 2018/6/15
 * @since 1.0.0
 * 〈坚持灵活 灵活坚持〉
 */
public class CustomUserService implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public UserDetails loadUserByUsername(String username) {
        logger.info("用户登录，获得用户名：{}", username);
        //1,根据用户名到数据库查询到user-->password
        SysUser sysUser = userService.findByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("User '" + username + "' not found");
        }
        List<SysRole> roleList = roleService.selectUserByRoleId(sysUser.getUserId());
        if (roleList != null && roleList.size() > 0) {
            if (sysUser.getRoleSet() == null) {
                sysUser.setRoleSet(new HashSet<>());
            }
            sysUser.getRoleSet().addAll(roleList);
        }

       /* //2,获取当前用户所拥有权限(模块)
        Set<SysModule> moduleSet = new HashSet<>(0);
        if (sysUser.getRoleSet() != null) {
            sysUser.getRoleSet().forEach(role -> {
                //获取到当前角色的所有模块
                moduleSet.addAll(role.getModuleSet());
            });
        }

        Set<SimpleGrantedAuthority> authorities = new HashSet<>(moduleSet.size());
        moduleSet.forEach(module -> {
            //3,将 module -> authority
            SimpleGrantedAuthority authorityGranter = new SimpleGrantedAuthority(module.getPermission());
            authorities.add(authorityGranter);
        });
*/

        Set<SimpleGrantedAuthority> authorities = new HashSet<>(sysUser.getRoleSet().size());
        sysUser.getRoleSet().forEach(module -> {
            SimpleGrantedAuthority authorityGranter = new SimpleGrantedAuthority(module.getName());
            authorities.add(authorityGranter);
        });

        User user = new User(username, sysUser.getPassword(), authorities);
        logger.info("user:{}", user);
        return user;
    }
}

